package com.kotodama.infrastructure.tenant.resolver;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

/**
 * 租户解析链，按优先级组合多个解析策略
 * 依次尝试提取租户标识，第一个成功解析的策略结果将被采用
 */
@Component
public class TenantResolverChain {

    private final List<TenantResolver> resolvers;

    public TenantResolverChain(List<TenantResolver> resolvers) {
        this.resolvers = resolvers;
    }

    /**
     * 按优先级依次尝试解析租户ID
     * 
     * @param request HTTP请求
     * @return 租户ID，如果所有解析器都失败则返回null
     */
    public String resolveTenantId(HttpServletRequest request) {
        for (TenantResolver resolver : resolvers) {
            String tenantId = resolver.resolveTenantId(request);
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                return tenantId.trim();
            }
        }
        return null;
    }

    /**
     * 获取所有可用的解析器
     * 
     * @return 解析器列表
     */
    public List<TenantResolver> getResolvers() {
        return List.copyOf(resolvers);
    }
}